package cc.yugu.yhdw.webserver.service.basic;

import cc.yugu.yhdw.common.constant.ConstEnum;
import cc.yugu.yhdw.common.constant.Constant;
import cc.yugu.yhdw.common.domain.basic.CustomerInOutMoney;
import cc.yugu.yhdw.common.domain.basic.DepositOrder;
import cc.yugu.yhdw.common.domain.basic.Passport;
import cc.yugu.yhdw.common.domain.basic.PassportInfo;
import cc.yugu.yhdw.common.domain.hdw.Battery;
import cc.yugu.yhdw.common.domain.hdw.Bicycle;
import cc.yugu.yhdw.common.entity.json.ExtResult;
import cc.yugu.yhdw.common.entity.pagination.Page;
import cc.yugu.yhdw.common.utils.CodecUtils;
import cc.yugu.yhdw.webserver.biz.client.ClientBizUtils;
import cc.yugu.yhdw.webserver.config.AppConfig;
import cc.yugu.yhdw.webserver.constant.AppConstant;
import cc.yugu.yhdw.webserver.persistence.basic.CustomerInOutMoneyMapper;
import cc.yugu.yhdw.webserver.persistence.basic.DepositOrderMapper;
import cc.yugu.yhdw.webserver.persistence.basic.PassportMapper;
import cc.yugu.yhdw.webserver.persistence.hdw.BatteryMapper;
import cc.yugu.yhdw.webserver.persistence.hdw.BicycleMapper;
import cc.yugu.yhdw.webserver.service.AbstractService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
 * 客户信息业务
 * 
 * @Date:Created in 2018/7/3 19:53
 * @Author:
 * @Modified By: zjn 2018/7/3 19:53
 */ 
@Service
public class PassportService extends AbstractService {
    @Autowired
    AppConfig config;
    @Autowired
    PassportMapper passportMapper;
    @Autowired
    BatteryMapper batteryMapper;
    @Autowired
    BicycleMapper bicycleMapper;
    @Autowired
    CustomerInOutMoneyMapper customerInOutMoneyMapper;
    @Autowired
    DepositOrderMapper depositOrderMapper;
    /**
    * 根据主键id查询表bas_passport 中指定字段信息
    * 
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.domain.basic.PassportInfo
    * @Author By: zjn 2018/7/3  19:53
    */ 
    public PassportInfo findInfo(int id) {
        return passportMapper.findInfo(id);
    }
    /**
    * 查询
    * 
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.domain.basic.Passport
    * @Author By: zjn 2018/7/3  19:54
    */ 
    public Passport find(int id) {
        // 根据客户id查询 1 条数据
        Bicycle bicycle = bicycleMapper.findByCustomer(id);
        // 根据主键查询
        Passport passport = passportMapper.find(id);
        if (passport != null) {
            if (bicycle != null) {
                passport.setBicycleId(bicycle.getId());
            }
        }
        return passport;
    }

    /**
    * 根据 指定格式的创建时间、运营商id、代理商id查询
    * 
    * @Param: [createTime, agentId, agencyId]
    * @Return: java.lang.Integer
    * @Author By: zjn 2018/7/4  10:04
    */ 
    public Integer findToDayTotal(Date createTime, Integer agentId, Integer agencyId) {
        return passportMapper.findToDayTotal(createTime, agentId, agencyId);
    }
    /**
    * 查询
    * 
    * @Param: [id, property, value]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/4  10:10
    */ 
    public ExtResult findUnique(Integer id, String property, Object value) {
        if (passportMapper.findUnique(id, property, value) == 0) {
            return ExtResult.successResult();
        } else {
            return ExtResult.failResult("数据重复");
        }
    }
    /**
    * 分页查询
    * 
    * @Param: [user]
    * @Return: cc.yugu.yhdw.common.entity.pagination.Page
    * @Author By: zjn 2018/7/4  10:11
    */ 
    public Page findPage(Passport user) {

        Page page = user.buildPage();
        page.setTotalItems(passportMapper.findPageCount(user));
        user.setBeginIndex(page.getOffset());
        page.setResult(passportMapper.findPageResult(user));
        return page;
    }
    /**
    * 客户注册（新增客户）
    * 
    * @Param: [customer]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/4  10:11
    */ 
    @Transactional(rollbackFor = Throwable.class)
    public ExtResult create(Passport customer) throws IOException {
        try {
            boolean unique = passportMapper.findUnique(customer.getId(), "mobile", customer.getMobile()) == 0;
            if (!unique) {
                return ExtResult.failResult("手机号已存在");
            }
            if (StringUtils.isNotEmpty(customer.getIdNo())) {
                unique = passportMapper.findUnique(customer.getId(), "idNo", customer.getIdNo()) == 0;
                if (!unique) {
                    return ExtResult.failResult("身份证号已存在");
                }
            }
            if (StringUtils.isNotEmpty(customer.getCardNo())) {
                unique = passportMapper.findUnique(customer.getId(), "cardNo", customer.getCardNo()) == 0;
                if (!unique) {
                    return ExtResult.failResult("卡号已存在");
                }
            }

            if (StringUtils.isEmpty(customer.getPassword())) {
                customer.setPassword(CodecUtils.password(Constant.DEFAULT_PASSWORD));
            } else {
                customer.setPassword(CodecUtils.password(customer.getPassword()));
            }

            if (StringUtils.isNotEmpty(customer.getPortrait())) {
                File source = new File(customer.getPortrait());
                if (source.exists()) {
                    File target = new File(config.portraitDir, source.getName());
                    FileUtils.copyFile(source, target);
                    // 客户头像设置
                    customer.setPortrait(AppConstant.PATH_PORTRAIT + target.getName());
                }
            }
            // 设置默认的余额
            customer.setBalance(0);
            // 设置默认的代金券
            customer.setExchangeBalance(0);
            customer.setCreateTime(new Date());
            customer.setLevel(1);
            // 设置默认的押金
            customer.setForegift(0);
            // 新建客户（老的方法是insert）
            passportMapper.insertAll(customer);
        } catch (IOException e) {
            return ExtResult.failResult("操作失败");
        }
        return ExtResult.successResult();
    }
    /**
    * 更新客户信息
    * 
    * @Param: [customer]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/4  10:12
    */ 
    public ExtResult update(Passport customer) throws IOException {
        try {
            boolean unique = passportMapper.findUnique(customer.getId(), "mobile", customer.getMobile()) == 0;
            if (!unique) {
                return ExtResult.failResult("手机号已存在");
            }
            // 如果身份证不为null
            if (StringUtils.isNotEmpty(customer.getIdNo())) {
                unique = passportMapper.findUnique(customer.getId(), "idNo", customer.getIdNo()) == 0;
                if (!unique) {
                    return ExtResult.failResult("身份证号已存在");
                }
            }
            if (StringUtils.isNotEmpty(customer.getCardNo())) {
                unique = passportMapper.findUnique(customer.getId(), "cardNo", customer.getCardNo()) == 0;
                if (!unique) {
                    return ExtResult.failResult("卡号已存在");
                }
            }

            if (StringUtils.isEmpty(customer.getPassword())) {
                customer.setPassword(null);
            } else {
                customer.setPassword(CodecUtils.password(customer.getPassword()));
            }

            if (StringUtils.isNotEmpty(customer.getPortrait()) && customer.getPortrait().startsWith(AppConstant.PATH_TEMP)) {
                File source = new File(customer.getPortrait());
                if (source.exists()) {
                    File target = new File(config.portraitDir, source.getName());
                    FileUtils.copyFile(source, target);
                    customer.setPortrait(AppConstant.PATH_PORTRAIT + target.getName());
                }
            }
            // 根据客户id查询客户信息
            Passport passport = passportMapper.find(customer.getId());
            // 用户信息变更通知
            boolean createFlag = false;
            boolean updateFlag = false;
            boolean deleteFlag = false;
            // 客户存在
            if (passport != null) {
                // 新增标志，表中的禁用状态为false和修改后的禁用状态为true--启用用户
                createFlag = passport.getActiveFlag().equals(ConstEnum.Flag.FALSE.getValue()) && customer.getActiveFlag().equals(ConstEnum.Flag.TRUE.getValue());
                // 更新标志，表中的禁用状态为true和修改后的禁用状态为true和 （手机号码不一致与密码不一致）--修改用户
                updateFlag = passport.getActiveFlag().equals(ConstEnum.Flag.TRUE.getValue()) && customer.getActiveFlag().equals(ConstEnum.Flag.TRUE.getValue()) && (!customer.getMobile().equals(passport.getMobile()) || (StringUtils.isNotEmpty(customer.getPassword()) && !passport.getPassword().equals(customer.getPassword())));
                // 删除标志，表中的禁用状态为true和修改后的禁用状态为false--禁用用户
                deleteFlag = passport.getActiveFlag().equals(ConstEnum.Flag.TRUE.getValue()) && customer.getActiveFlag().equals(ConstEnum.Flag.FALSE.getValue());
            }
            //int total = passportMapper.update(customer);
            int total = passportMapper.updateAge(customer);


            // 更新客户
            //int total = passportMapper.update(customer);

            if (total != 0) {
                // 修改余额
                customer.setBalance(passport.getBalance());
                if (createFlag) {
                    // 启用通知
                    if (StringUtils.isEmpty(customer.getPassword())) {
                        customer.setPassword(passport.getPassword());
                    }
                    List<Passport> createList = new ArrayList<Passport>();
                    createList.add(customer);
                    // 查询客户关联的柜机
                    List<String> cabinetIds = findByCustomerId(customer.getId());
                    ClientBizUtils.noticeCustomer(config, cabinetIds, createList, Collections.EMPTY_LIST, Collections.EMPTY_LIST);
                }else if (updateFlag) {
                    //修改通知
                    if (StringUtils.isEmpty(customer.getPassword())) {
                        customer.setPassword(passport.getPassword());
                    }
                    List<Passport> updateList = new ArrayList<Passport>();
                    updateList.add(customer);
                    List<String> cabinetIds = findByCustomerId(customer.getId());
                    ClientBizUtils.noticeCustomer(config, cabinetIds, Collections.EMPTY_LIST, updateList, Collections.EMPTY_LIST);
                } else if (deleteFlag) {
                    // 禁用通知
                    List<Passport> deleteList = new ArrayList<Passport>();
                    deleteList.add(passport);
                    List<String> cabinetIds = findByCustomerId(customer.getId());
                    ClientBizUtils.noticeCustomer(config, cabinetIds, Collections.EMPTY_LIST, Collections.EMPTY_LIST, deleteList);
                }
            }
        } catch (IOException e) {
            return ExtResult.failResult("操作失败");
        }
        return ExtResult.successResult();
    }
    /**
    * 充值
    * 
    * @Param: [id, money, depositOrderId]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/4  10:24
    */ 
    @Transactional(rollbackFor = Throwable.class)
    public ExtResult recharge(int id, float money, String depositOrderId) {
        try {
            Passport customer = passportMapper.find(id);
            if (customer == null) {
                return ExtResult.failResult("客户不存在");
            }
            int reexchangeMoney = (int) (money * 100);
            // 根据主键更新余额
            int result = passportMapper.updateBalance(id, reexchangeMoney);
            if (result < 0) {
                return ExtResult.failResult("操作失败");
            }
            CustomerInOutMoney customerInOutMoney = new CustomerInOutMoney();
            customerInOutMoney.setCustomerId(id);
            customerInOutMoney.setMoney(reexchangeMoney);
            customerInOutMoney.setBizType(CustomerInOutMoney.BizType.IN_MONEY_OFFLINE.getValue());
            customerInOutMoney.setSourceId(depositOrderId);
            customerInOutMoney.setCreateTime(new Date());
            customerInOutMoneyMapper.insert(customerInOutMoney);

            DepositOrder deposit = new DepositOrder();
            deposit.setId(depositOrderId);
            deposit.setBizType(DepositOrder.BizType.OFFLINE.getValue());
            deposit.setMoney(reexchangeMoney);
            deposit.setStatus(DepositOrder.Status.SUCCESS.getValue());
            deposit.setCreateTime(new Date());
            deposit.setHandleTime(new Date());

            deposit.setCustomerId(id);
            depositOrderMapper.insert(deposit);
        } catch (Exception e) {
            return ExtResult.failResult("操作失败");
        }
        return ExtResult.successResult();

    }
}
